package vin.pth.example.service;

import java.util.Map;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class RestService {

  @Autowired
  private TestRestTemplate restTemplate;

  public ResponseEntity<String> get(String url, Map<String, String> param) {
    return this.get(url, param, null);
  }

  public ResponseEntity<String> get(String url, Map<String, String> param, String token) {
    HttpHeaders headers = new HttpHeaders();
    if (StringUtils.hasText(token)) {
      headers.add("token", token);
    }
    HttpEntity<String> httpEntity = new HttpEntity<>(headers);
    return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
  }

  public ResponseEntity<String> post(String url, Map<String, String> param) {
    return this.post(url, param, null);
  }

  public ResponseEntity<String> post(String url, Map<String, String> param, String token) {
    JSONObject json = new JSONObject();
    json.putAll(param);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    if (StringUtils.hasText(token)) {
      headers.add("token", token);
    }
    HttpEntity<JSONObject> request = new HttpEntity<>(json, headers);
    return restTemplate.postForEntity(url, request, String.class);
  }

}
